# -*- coding: utf-8 -*-
import math


def out_of_china(lng, lat):
    """判断是否在国内，不在国内不做偏移"""
    return not (72.004 <= lng <= 137.8347 and 0.8293 <= lat <= 55.8271)


def transformLat(x, y):
    ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * math.sqrt(abs(x))
    ret += (20.0 * math.sin(6.0 * x * math.pi) + 20.0 * math.sin(2.0 * x * math.pi)) * 2.0 / 3.0
    ret += (20.0 * math.sin(y * math.pi) + 40.0 * math.sin(y / 3.0 * math.pi)) * 2.0 / 3.0
    ret += (160.0 * math.sin(y / 12.0 * math.pi) + 320 * math.sin(y * math.pi / 30.0)) * 2.0 / 3.0
    return ret


def transformLng(x, y):
    ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * math.sqrt(abs(x))
    ret += (20.0 * math.sin(6.0 * x * math.pi) + 20.0 * math.sin(2.0 * x * math.pi)) * 2.0 / 3.0
    ret += (20.0 * math.sin(x * math.pi) + 40.0 * math.sin(x / 3.0 * math.pi)) * 2.0 / 3.0
    ret += (150.0 * math.sin(x / 12.0 * math.pi) + 300.0 * math.sin(x / 30.0 * math.pi)) * 2.0 / 3.0
    return ret


def delta(lng, lat):
    """计算GCJ-02与WGS-84之间的转换误差"""
    a = 6378245.0  # 长半轴
    ee = 0.00669342162296594323  # 扁率

    dLat = transformLat(lng - 105.0, lat - 35.0)
    dLng = transformLng(lng - 105.0, lat - 35.0)

    radLat = lat / 180.0 * math.pi
    magic = math.sin(radLat)
    magic = 1 - ee * magic * magic
    sqrtMagic = math.sqrt(magic)

    dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * math.pi)
    dLng = (dLng * 180.0) / (a / sqrtMagic * math.cos(radLat) * math.pi)

    return {'lng': dLng, 'lat': dLat}


def gcj02_to_wgs84(lng, lat):
    """GCJ-02转WGS-84"""
    if out_of_china(lng, lat):
        return lng, lat

    d = delta(lng, lat)
    return lng - d['lng'], lat - d['lat']


# 使用示例
gcj_lng = 103.059168
gcj_lat = 29.999844
wgs_lng, wgs_lat = gcj02_to_wgs84(gcj_lng, gcj_lat)
print "WGS-84坐标:", wgs_lng, wgs_lat
